package Hot100;

import Tree.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class 二叉树展开为链表 {

    private Queue<TreeNode> queue = new LinkedList<>();
    private TreeNode pre = null;

    public void flatten(TreeNode root) {
        /* 时间复杂度：O(n) 空间复杂度：O(1) */
        /*TreeNode cur = root;
        while (cur != null) {
            if (cur.left != null) {
                TreeNode connect = cur.left;
                while (connect.right != null) connect = connect.right;
                connect.right = cur.right;
                cur.right = cur.left;
                cur.left = null;
            }
            cur = cur.right;
        }*/

        /* 时间复杂度：O(n) 空间复杂度：O(n) */
        preOrder(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            node.left = null;
            node.right = queue.peek();
        }

        /* 时间复杂度：O(n) 空间复杂度：O(n) */
        if (root == null) return;
        flatten(root.right);
        flatten(root.left);
        root.right = pre;
        root.left = null;
        pre = root;
    }

    private void preOrder(TreeNode root) {
        if (root == null) return;
        queue.offer(root);
        preOrder(root.left);
        preOrder(root.right);
    }
}
